package sharetime.core;

import org.hibernate.validator.ClassValidator;
import org.hibernate.validator.InvalidValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sharetime.playlist.domain.Playlist;
import sharetime.user.domain.User;

@SuppressWarnings("unchecked")
public class AnnotationValidator {
	private static Logger logger = LoggerFactory
			.getLogger(AnnotationValidator.class);

	// It is considered a good practice to execute these lines once and
	// cache the validator instances.
	public static final ClassValidator<User> USER_VALIDATOR = new ClassValidator<User>(
			User.class);
	public static final ClassValidator<Playlist> PLAYLIST_VALIDATOR = new ClassValidator<Playlist>(
			Playlist.class);

	private static ClassValidator<? extends EntityObject> getValidator(
			Class<? extends EntityObject> clazz) {
		if (User.class.equals(clazz)) {
			return USER_VALIDATOR;
		}else if(Playlist.class.equals(clazz)){
			return PLAYLIST_VALIDATOR;
		}else {
			throw new IllegalArgumentException("Unsupported class was passed.");
		}
	}

	public static InvalidValue[] getInvalidValues(EntityObject modelObject) {
		String nullProperty = null;
		return getInvalidValues(modelObject, nullProperty);
	}

	public static InvalidValue[] getInvalidValues(EntityObject modelObject,
			String property) {
		Class<? extends EntityObject> clazz = modelObject.getClass();
		ClassValidator validator = getValidator(clazz);

		InvalidValue[] validationMessages;

		if (property == null) {
			validationMessages = validator.getInvalidValues(modelObject);
		} else {
			// only get invalid values for specified property.
			// For example, "city" applies to getCity() method.
			validationMessages = validator.getInvalidValues(modelObject,
					property);
		}
		return validationMessages;
	}

}
